<template>
  <div class="event-monitoring-panel">
    <!-- 统计卡片 -->
    <a-row :gutter="16" style="margin-bottom: 24px">
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="总事件数"
            :value="statistics.totalEvents"
            :value-style="{ color: '#3f8600' }"
          >
            <template #prefix>
              <IconifyIcon icon="ant-design:cluster-outlined" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="今日事件"
            :value="statistics.todayEvents"
            :value-style="{ color: '#1890ff' }"
          >
            <template #prefix>
              <IconifyIcon icon="ant-design:calendar-outlined" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="处理成功率"
            :value="statistics.successRate"
            :precision="2"
            suffix="%"
            :value-style="{ color: '#52c41a' }"
          >
            <template #prefix>
              <IconifyIcon icon="ant-design:check-circle-outlined" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="平均处理时间"
            :value="statistics.avgProcessTime"
            suffix="ms"
            :value-style="{ color: '#722ed1' }"
          >
            <template #prefix>
              <IconifyIcon icon="ant-design:clock-circle-outlined" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 工具栏 -->
    <div class="toolbar">
      <a-space>
        <a-button type="primary" @click="refreshData">
          <template #icon>
            <IconifyIcon icon="ant-design:reload-outlined" />
          </template>
          刷新
        </a-button>
        <a-button @click="showAlertModal">
          <template #icon>
            <IconifyIcon icon="ant-design:alert-outlined" />
          </template>
          告警配置
        </a-button>
      </a-space>

      <a-space>
        <a-range-picker
          :value="dateRange"
          @change="handleDateRangeChange"
          style="width: 240px"
        />
        <a-select
          :value="filterType"
          placeholder="事件类型"
          style="width: 150px"
          @change="handleFilter"
        >
          <a-select-option value="">全部类型</a-select-option>
          <a-select-option
            v-for="type in eventTypes"
            :key="type.value"
            :value="type.value"
          >
            {{ type.label }}
          </a-select-option>
        </a-select>
      </a-space>
    </div>

    <!-- 事件监控列表 -->
    <a-table
      :columns="columns"
      :data-source="monitoringData"
      :loading="loading"
      :pagination="pagination"
      row-key="id"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'eventType'">
          <a-tag :color="getEventTypeColor(record.eventType)">
            {{ getEventTypeLabel(record.eventType) }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'status'">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusLabel(record.status) }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'priority'">
          <a-tag :color="getPriorityColor(record.priority)">
            {{ getPriorityLabel(record.priority) }}
          </a-tag>
        </template>

        <template v-else-if="column.key === 'processTime'">
          <span :style="{ color: getProcessTimeColor(record.processTime) }">
            {{ record.processTime }}ms
          </span>
        </template>

        <template v-else-if="column.key === 'actions'">
          <a-space>
            <a-button type="link" size="small" @click="showDetailModal(record)">
              详情
            </a-button>
            <a-button
              v-if="record.status === 'FAILED'"
              type="link"
              size="small"
              @click="handleRetry(record.id)"
            >
              重试
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 告警配置模态框 -->
    <a-modal
      :open="alertModalVisible"
      title="告警配置"
      width="600px"
      @ok="handleAlertSave"
      @cancel="closeAlertModal"
    >
      <a-form layout="vertical">
        <a-form-item label="事件处理失败告警">
          <a-switch v-model:checked="alertConfig.failureAlert" />
        </a-form-item>
        <a-form-item label="处理时间超时告警">
          <a-switch v-model:checked="alertConfig.timeoutAlert" />
        </a-form-item>
        <a-form-item label="超时阈值（毫秒）">
          <a-input-number
            v-model:value="alertConfig.timeoutThreshold"
            :min="1000"
            :max="60000"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="告警通知邮箱">
          <a-input
            v-model:value="alertConfig.alertEmail"
            placeholder="请输入告警通知邮箱"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 事件详情模态框 -->
    <a-modal
      :open="detailModalVisible"
      title="事件详情"
      width="800px"
      @cancel="closeDetailModal"
      :footer="null"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="事件ID">
          {{ selectedEvent?.id }}
        </a-descriptions-item>
        <a-descriptions-item label="事件名称">
          {{ selectedEvent?.name }}
        </a-descriptions-item>
        <a-descriptions-item label="事件类型">
          <a-tag :color="getEventTypeColor(selectedEvent?.eventType)">
            {{ getEventTypeLabel(selectedEvent?.eventType) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="优先级">
          <a-tag :color="getPriorityColor(selectedEvent?.priority)">
            {{ getPriorityLabel(selectedEvent?.priority) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="getStatusColor(selectedEvent?.status)">
            {{ getStatusLabel(selectedEvent?.status) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="处理时间">
          {{ selectedEvent?.processTime }}ms
        </a-descriptions-item>
        <a-descriptions-item label="触发时间" :span="2">
          {{ selectedEvent?.triggerTime }}
        </a-descriptions-item>
        <a-descriptions-item label="事件数据" :span="2">
          <pre>{{ selectedEvent?.eventData }}</pre>
        </a-descriptions-item>
        <a-descriptions-item label="处理结果" :span="2">
          <pre>{{ selectedEvent?.processResult }}</pre>
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

// Props
interface Props {
  resourceId: string;
  resourceType: string;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  'event-processed': [event: any];
}>();

// 响应式数据
const loading = ref(false);
const alertModalVisible = ref(false);
const detailModalVisible = ref(false);
const selectedEvent = ref<any>(null);
const dateRange = ref([]);
const filterType = ref('');

// 统计数据
const statistics = ref({
  totalEvents: 1250,
  todayEvents: 45,
  successRate: 98.5,
  avgProcessTime: 125,
});

// 告警配置
const alertConfig = reactive({
  failureAlert: true,
  timeoutAlert: true,
  timeoutThreshold: 5000,
  alertEmail: 'admin@example.com',
});

// 事件类型
const eventTypes = [
  { value: 'CREATE', label: '创建事件' },
  { value: 'UPDATE', label: '更新事件' },
  { value: 'DELETE', label: '删除事件' },
  { value: 'START', label: '启动事件' },
  { value: 'STOP', label: '停止事件' },
  { value: 'ERROR', label: '错误事件' },
  { value: 'WARNING', label: '警告事件' },
  { value: 'INFO', label: '信息事件' },
  { value: 'CUSTOM', label: '自定义事件' },
];

// 模拟监控数据
const monitoringData = ref([
  {
    id: '1',
    name: '资源创建事件',
    eventType: 'CREATE',
    priority: 'MEDIUM',
    status: 'SUCCESS',
    processTime: 120,
    triggerTime: '2024-01-15 10:30:00',
    eventData: '{"resourceId": "res_001", "action": "create"}',
    processResult: '{"success": true, "message": "资源创建成功"}',
  },
  {
    id: '2',
    name: '资源状态变更事件',
    eventType: 'UPDATE',
    priority: 'HIGH',
    status: 'SUCCESS',
    processTime: 85,
    triggerTime: '2024-01-15 11:00:00',
    eventData:
      '{"resourceId": "res_002", "oldStatus": "CREATED", "newStatus": "RUNNING"}',
    processResult: '{"success": true, "message": "状态更新成功"}',
  },
  {
    id: '3',
    name: '系统错误事件',
    eventType: 'ERROR',
    priority: 'URGENT',
    status: 'FAILED',
    processTime: 2500,
    triggerTime: '2024-01-15 11:30:00',
    eventData: '{"errorCode": "E001", "errorMessage": "数据库连接失败"}',
    processResult: '{"success": false, "message": "处理失败"}',
  },
  {
    id: '4',
    name: '系统警告事件',
    eventType: 'WARNING',
    priority: 'MEDIUM',
    status: 'SUCCESS',
    processTime: 95,
    triggerTime: '2024-01-15 12:00:00',
    eventData: '{"warningType": "RESOURCE_USAGE", "usage": 85}',
    processResult: '{"success": true, "message": "警告已处理"}',
  },
]);

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 表格列配置
const columns = [
  {
    title: '事件名称',
    dataIndex: 'name',
    key: 'name',
    width: 180,
  },
  {
    title: '事件类型',
    dataIndex: 'eventType',
    key: 'eventType',
    width: 120,
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    key: 'priority',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '处理时间',
    dataIndex: 'processTime',
    key: 'processTime',
    width: 120,
  },
  {
    title: '触发时间',
    dataIndex: 'triggerTime',
    key: 'triggerTime',
    width: 160,
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    fixed: 'right',
  },
];

// 方法
const loadData = () => {
  loading.value = true;
  setTimeout(() => {
    pagination.value.total = monitoringData.value.length;
    loading.value = false;
  }, 500);
};

const refreshData = () => {
  loadData();
  message.success('数据刷新成功');
};

const showAlertModal = () => {
  alertModalVisible.value = true;
};

const closeAlertModal = () => {
  alertModalVisible.value = false;
};

const handleAlertSave = () => {
  message.success('告警配置保存成功');
  closeAlertModal();
};

const handleDateRangeChange = (dates: any) => {
  dateRange.value = dates;
  loadData();
};

const handleFilter = (value: string) => {
  filterType.value = value;
  loadData();
};

const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  loadData();
};

const showDetailModal = (record: any) => {
  selectedEvent.value = record;
  detailModalVisible.value = true;
};

const closeDetailModal = () => {
  detailModalVisible.value = false;
  selectedEvent.value = null;
};

const handleRetry = (id: string) => {
  message.success(`事件 ${id} 重试功能开发中...`);
};

const getEventTypeLabel = (type: string) => {
  const eventType = eventTypes.find((t) => t.value === type);
  return eventType?.label || type;
};

const getEventTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    CREATE: 'green',
    UPDATE: 'blue',
    DELETE: 'red',
    START: 'cyan',
    STOP: 'orange',
    ERROR: 'red',
    WARNING: 'orange',
    INFO: 'blue',
    CUSTOM: 'purple',
  };
  return colorMap[type] || 'default';
};

const getPriorityLabel = (priority: string) => {
  const priorityMap: Record<string, string> = {
    LOW: '低',
    MEDIUM: '中',
    HIGH: '高',
    URGENT: '紧急',
  };
  return priorityMap[priority] || priority;
};

const getPriorityColor = (priority: string) => {
  const colorMap: Record<string, string> = {
    LOW: 'default',
    MEDIUM: 'blue',
    HIGH: 'orange',
    URGENT: 'red',
  };
  return colorMap[priority] || 'default';
};

const getStatusLabel = (status: string) => {
  const statusMap: Record<string, string> = {
    PENDING: '待处理',
    PROCESSING: '处理中',
    SUCCESS: '成功',
    FAILED: '失败',
    CANCELLED: '已取消',
  };
  return statusMap[status] || status;
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    PENDING: 'default',
    PROCESSING: 'blue',
    SUCCESS: 'green',
    FAILED: 'red',
    CANCELLED: 'orange',
  };
  return colorMap[status] || 'default';
};

const getProcessTimeColor = (time: number) => {
  if (time < 100) return '#52c41a';
  if (time < 500) return '#1890ff';
  if (time < 1000) return '#faad14';
  return '#f5222d';
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style lang="less" scoped>
.event-monitoring-panel {
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
  }

  pre {
    background: #f5f5f5;
    padding: 8px;
    border-radius: 4px;
    font-size: 12px;
    max-height: 200px;
    overflow: auto;
  }
}
</style>
